package com.example.teacher.controller;


import com.alibaba.excel.util.StringUtils;
import com.example.commonutils.ResultData;
import com.example.servicebase.client.VodClient;
import com.example.teacher.entity.EduVideo;
import com.example.teacher.service.EduVideoService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-05-25
 */
@RestController
@RequestMapping("/backstage/video")
public class EduVideoController {

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private VodClient client;

    //    添加小节
    @PostMapping(value = "addVideo",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultData addVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.save(eduVideo);
        return ResultData.ok();
    }

    //删除小节
    @DeleteMapping(value = "deleteVideo/{id}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultData deleteVideo(@PathVariable String id) {

        //根据小节id查询出视频id
        EduVideo video = eduVideoService.getById(id);
        //拿到视频id
        String videoId = video.getVideoSourceId();
//        判断是否为空
        if(!StringUtil.isNullOrEmpty(videoId)) {
            //不为空则发起远程调用删除视频
            client.removeVideo(videoId);
        }
        //然后删除小节
        eduVideoService.removeById(id);
        return ResultData.ok();
    }

    //修改小节
    @PostMapping(value = "updateVideo",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultData updateVideo(@RequestBody EduVideo eduVideo) {
        //先查看视频id是否为空，为空则表示没有重新上传视频
        if (StringUtils.isEmpty(eduVideo.getVideoSourceId())) {
            //为空则直接更新
            eduVideoService.updateById(eduVideo);
        } else {
            //如果不为空，则查询数据库，看已存在的记录是否为空
            EduVideo video = eduVideoService.getById(eduVideo.getId());
            //查看数据库中的记录的视频id是否为空
            if (StringUtils.isEmpty(video.getVideoSourceId())) {
                //为空则直接更新，不产生冲突
                eduVideoService.updateById(eduVideo);
            } else {
                //更新数据库数据
                eduVideoService.updateById(eduVideo);
                //数据库中的记录已经有视频，则需要删除旧视频，添加新视频
                client.removeVideo(video.getVideoSourceId());
                return ResultData.ok();
            }
        }
        return ResultData.error();
    }
}

